import { AuthService } from '@service/auth.service';
import { BaseService } from '@service/base.service';
import { AbsFormUtil } from '@abstract/form';
import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { FormBuilder } from '@angular/forms';
import { IBaseTag } from '@model/base';
import { deepClone } from '@utils/lang';
const ID = '123456789';
@Component({
	selector: 'app-base-tag',
	templateUrl: './base-tag.component.html',
	styleUrls: ['./base-tag.component.less']
})
export class BaseTagComponent extends AbsFormUtil implements OnInit {
	nzLoading = false;
	data = [];
	editData: IBaseTag = null;

	
	constructor(
		private baseService: BaseService,
		private nzMessageService: NzMessageService,
		private fb: FormBuilder,
		private authService: AuthService
	) {
		super();
		this.page.limit = 1000;
		this.authList = this.authService.getAuth();

	}

	ngOnInit() {
		this.buildForm();
		this.onSearch();
	}
	buildForm() {
		this.validateForm = this.fb.group({
			tagName: ['']
		});
	}

	async onSearch(isPageInit?: boolean) {
		this.nzLoading = true;
		if (isPageInit) {
			this.page.page = 1;
		}
		const params = { ...this.validateForm.value };
		const result = await this.baseService.getHouseholdTagList(params);
		this.data = result.data;
		this.page.total = result.data.length;
		this.nzLoading = false;

	}



	create() {
		if (this.editData && this.editData.id) {
			this.nzMessageService.info('请一次编辑一条数据');
			return;
		}
		this.editData = new IBaseTag();
		this.editData.id = ID;
		this.data.unshift(this.editData);
		this.data = [...this.data];
	}
	async del(item: IBaseTag) {
		const result = await this.baseService.deleteHouseholdTag(item.id);
		this.nzMessageService.success('删除成功');
		const idx = this.data.findIndex(it => it.id === item.id);
		this.data.splice(idx, 1);
		this.data = [...this.data];
	}
	cancel() {
		if (this.editData.id === ID) {
			this.data.shift();
			this.data = [...this.data];
		}
		this.editData = null;
	}
	edit(item: IBaseTag) {
		if (this.editData && this.editData.id) {
			this.nzMessageService.info('请一次编辑一条数据');
			return;
		}
		this.editData = deepClone(item);
	}

	async save(item: IBaseTag) {
		const editData = this.editData;
		const isCreate = editData.id === ID;
		if (isCreate) {
			editData.id = null;
		}
		await this.baseService.saveHouseholdTag(editData)
		isCreate ? this.onSearch(true) : Object.assign(item, editData);
		this.editData = new IBaseTag();
		this.nzMessageService.success('保存成功');
	}

}
